package com.acme.superchat;

import com.acme.superchat.service.server.ChatWorker;
import com.acme.superchat.service.server.SharedServer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.*;

/**
 * Start chat server
 *
 * @author Gregory Sobko
 */
public class ChatServer {
    public final static int PORT = 4321;
    private static SharedServer sharedServer;


    /**
     * Start chat server
     *
     * @param args
     */
    public static void main(String... args) {
        Logger logger = Logger.getLogger("MyServerLogger");
        LogManager logManager = LogManager.getLogManager();
        logManager.addLogger(logger);

        logger = logManager.getLogger("MyServerLogger");

        if (logger == null) {
            System.exit(1);
        }

        try {
            FileHandler fileHandler = new FileHandler("error.log");
            ConsoleHandler consoleHandler = new ConsoleHandler();
            fileHandler.setLevel(Level.INFO);
            consoleHandler.setLevel(Level.FINEST);
            logger.addHandler(fileHandler);
            logger.addHandler(consoleHandler);

            try (ServerSocket acceptor = new ServerSocket(ChatServer.PORT)) {
                Class.forName("org.apache.derby.jdbc.ClientDriver");
                Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/DB;create=true", "user", "user");
                sharedServer = new SharedServer(conn);
                while (true) {
                    Socket clientSocket = acceptor.accept();

                    try {
                        ChatWorker chatWorker = new ChatWorker(clientSocket, sharedServer);
                        sharedServer.addWorker(chatWorker);
                        System.out.println("Client was accepted!");
                    } catch (IOException e) {
                        clientSocket.close();
                        e.printStackTrace();
                    }
                }
            } catch (SQLException e) {
                //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                logger.log(Level.INFO, e.getMessage());
            } catch (ClassNotFoundException e) {
                //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                logger.log(Level.INFO, e.getMessage());
            } finally {
                fileHandler.close();
                consoleHandler.close();
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


    }
}
